package com.example.android_app.network.mqtt.opp;

import java.util.Arrays;
import java.util.Iterator;

import android.R;

import com.example.android_app.GameActivity;
import com.example.android_app.struc.Update;
import com.ibm.mqtt.IMqttClient;
import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.ibm.mqtt.MqttPersistence;
import com.ibm.mqtt.MqttPersistenceException;
import com.ibm.mqtt.MqttSimpleCallback;
import com.pervasive.project.unified.data.constants.Constants;

public class MQTTConnection implements MqttSimpleCallback
{
	private static int				MQTT_BROKER_PORT_NUM      = 1883;
	private static MqttPersistence	MQTT_PERSISTENCE          = null;
	private static boolean			MQTT_CLEAN_START          = true;
	private static short			MQTT_KEEP_ALIVE           = 60 * 15;
	private static int[]			MQTT_QUALITIES_OF_SERVICE = { 0 } ;
	
	IMqttClient mqttClient = null;
	GameActivity gameActivity = null;
	
	public MQTTConnection(String brokerHostName, String userName, String dataLine, GameActivity gameActivity) 
	{
		this.gameActivity = gameActivity;
		
		String mqttConnSpec = "tcp://" + brokerHostName + "@" + MQTT_BROKER_PORT_NUM;
		try
		{
			mqttClient = MqttClient.createMqttClient(mqttConnSpec, MQTT_PERSISTENCE);
			
			mqttClient.connect(userName, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);
			
			mqttClient.registerSimpleHandler(this);
			
			subscribeToTopic(dataLine);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(" MQTTConnnection failed");
		}
	}

	private void subscribeToTopic(String dataLine) throws MqttException 
	{
		
			String[] topics = { dataLine };
			mqttClient.subscribe(topics, MQTT_QUALITIES_OF_SERVICE);
	}
	
	public void closeConnection()
	{
		/*try {
			//mqttClient.disconnect();
			mqttClient.terminate();
		} catch (MqttPersistenceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		mqttClient.terminate();
	}
	
	@Override
	public void connectionLost() throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void publishArrived(String dataLine, byte[] message, int qos, boolean val)
			throws Exception {
		// TODO Auto-generated method stub
		String mssg = new String(message);
		// TODO consume the message in depth
		System.out.println(" >>>>>> "+mssg);
		
		Iterator<String> mssgIte = Arrays.asList(mssg.split(",")).iterator();
		Update update = new Update();
		
		/*while(mssgIte.hasNext())
		{
			update.setUserName(mssgIte.next());
		}*/
		
		update.setUserName(mssgIte.next());
		update.setCardId(Constants.cardId.valueOf(mssgIte.next()));
		update.setCardStar(Constants.cardStar.valueOf(mssgIte.next()));
		
		gameActivity.update(update);
	}

}
